package com.stackroute.userservice.service;

import com.stackroute.userservice.exception.UserAlreadyExistsException;
import com.stackroute.userservice.exception.UserNotFoundException;
import com.stackroute.userservice.model.User;
import com.stackroute.userservice.repository.UserAutheticationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserAuthenticationServiceImpl implements UserAuthenticationService {


	@Autowired
	private UserAutheticationRepository autheticationRepository;

	public UserAuthenticationServiceImpl(UserAutheticationRepository autheticationRepository) {
		this.autheticationRepository = autheticationRepository;
	}


	@Override
	public User findByUserIdAndPassword(String userId, String password) throws UserNotFoundException {
		User fetchedUser = autheticationRepository.findByUserIdAndUserPassword(userId, password);
		if (fetchedUser == null) {
			throw new UserNotFoundException("User Not Found");
		}
		return fetchedUser;
	}


	@Override
	public boolean saveUser(User user) throws UserAlreadyExistsException {
		try {
			User fetchedUser = autheticationRepository.findById(user.getUserId()).orElse(null);
			if (fetchedUser != null) {
				throw new UserAlreadyExistsException("User Already Exists");
			}
			User u = autheticationRepository.save(user);
			if (u == null) {
				return false;
			}
			return true;
		} catch (Exception e) {
			throw new UserAlreadyExistsException("User Already Exists");
		}
	}
}
